package com.app.controller;

import cn.hutool.json.JSONObject;
import com.app.model.*;
import com.app.service.*;
import com.app.util.Result;
import com.app.util.WxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Controller
@ResponseBody
public class TemplateMessageController {
    @Autowired
    private TemplateMessageService templateMessageService;
    @Autowired
    private JobIntentionService jobIntentionService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private UserService userService;
    @Autowired
    private JobPublishService jobPublishService;
    @Autowired
    private EnterpriseService enterpriseService;

    //岗位信息审核
    public Result<SendModel> JobReview(com.alibaba.fastjson.JSONObject data, String openid) {
        //设置接收订阅消息
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("touser", openid);//接收者（用户）的 openid
        params.put("template_id", "SbpnxgSI_bHXA-GCrmMjgdG5W5TLB89O5qIwk1Shfy8");//所需下发的订阅模板id
        params.put("page", "/page_other/position/position_manage");//点击模板卡片后的跳转页面，仅限本小程序内的页面
        params.put("miniprogram_state", "formal");//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        params.put("lang", "zh_CN");//进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN返回值
        SendModel sendModel = WxUtil.sendCommonSubscribeMessage(params, data);//调用发送
        return Result.success(sendModel);
    }

    //面试邀请通知
    public Result<SendModel> interviewNotice() {
        //设置接收订阅消息
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("touser", "oMo_v5HXxhD1OK0GzxJMn7B8SjJY");//接收者（用户）的 openid
        params.put("template_id", "XMGjIF0XxYMdGUWH5C25Qv8sdY9Ffg2c6WYdSqY5DuE");//所需下发的订阅模板id
        params.put("page", "/page_other/position/position_manage"); //点击模板卡片后的跳转页面，仅限本小程序内的页面
        params.put("miniprogram_state", "trial");//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        params.put("lang", "zh_CN");//进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN返回值
        /**
         * data:小程序模板数据
         * 订阅消息参数值内容限制说明
         thing.DATA:20个以内字符;可汉字、数字、字母或符号组合
         time.DATA:24小时制时间格式（支持+年月日），支持填时间段，两个时间点之间用“~”符号连接
         */
        com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
        //邀请企业
        JSONObject thing1 = new JSONObject();
        thing1.put("value", "四川久远银海软件股份公司");
        data.put("thing1", thing1);
        //面试地址
        JSONObject thing2 = new JSONObject();
        thing2.put("value", "广州市天河区佳都商务大厦");
        data.put("thing2", thing2);
        //面试时间
        JSONObject date3 = new JSONObject();
        date3.put("value", "2019年11月20日14:00:00");
        data.put("date3", date3);
        //联系电话
        JSONObject phone_number5 = new JSONObject();
        phone_number5.put("value", "18229549305");
        data.put("phone_number5", phone_number5);
        //岗位名称
        JSONObject thing6 = new JSONObject();
        thing6.put("value", "硬件设计工程师");
        data.put("thing6", thing6);
        SendModel sendModel = WxUtil.sendCommonSubscribeMessage(params, data);//调用发送
        return Result.success(sendModel);
    }

    //企业端
    //岗位信息审核通知
    //机构审核消息提醒
    //个人端
    //职位推荐通知
    public void RecommendedPositions(com.alibaba.fastjson.JSONObject data, String openid) {
        //设置接收订阅消息
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("touser", openid);//接收者（用户）的 openid
        params.put("template_id", "oV_7y2wuuTl9a8Hzut-q3AKOYOfT9gcbj4aRVTEGdjQ");//所需下发的订阅模板id
        params.put("page", "pages/found/index");//点击模板卡片后的跳转页面，仅限本小程序内的页面
        params.put("miniprogram_state", "formal");//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        params.put("lang", "zh_CN");//进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN返回值
        WxUtil.sendCommonSubscribeMessage(params, data);//调用发送
    }

    //请求联系方式通知
    //新招聘职位通知
    public void NewPosition(com.alibaba.fastjson.JSONObject data, String openid) {
        //设置接收订阅消息
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("touser", openid);//接收者（用户）的 openid
        params.put("template_id", "-CJz0Q-ycXpKb-hPOXGqPY7bkuBi8njg4lfRZODPZNw");//所需下发的订阅模板id
        params.put("page", "pages/found/index");//点击模板卡片后的跳转页面，仅限本小程序内的页面
        params.put("miniprogram_state", "formal");//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        params.put("lang", "zh_CN");//进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN返回值
        WxUtil.sendCommonSubscribeMessage(params, data);//调用发送
    }

    //招聘会开始通知
    //职位申请通知
    //面试邀请通知
    @GetMapping("/abc")
    public void NewPosition() {
        try {
            //获取求职意向
            List<JobIntentionModel> jobIntentionModels = jobIntentionService.selectAll();
            List<SendModel> sendModels = new ArrayList<>();
            for (int i = 0; i < jobIntentionModels.size(); i++) {
                CustomerModel customerById = customerService.getCustomerById(jobIntentionModels.get(i).customerId);
                UserModel userByCustomerId = userService.getUserByCustomerId(customerById.getId());
                SendModel model = new SendModel();
                model.setOpenid(userByCustomerId.getOpenid());
                model.setPost(jobIntentionModels.get(i).getPost());
                List<JobPublishModel> jobByPostList = jobPublishService.findJobByPostList(model.getPost());
                Random random = new Random();
                if (jobByPostList.size() != 0) {
                    int i1 = random.nextInt(jobByPostList.size());
                    model.setJobPublishModel(jobByPostList.get(i1));
                    EnterpriseModel modelById = enterpriseService.findModelById(jobByPostList.get(i1).getEnrollId());
                    model.setEnterpriseModel(modelById);
                    sendModels.add(model);
                }
            }

            for (int i = 0; i < sendModels.size(); i++) {

                if (isToday(String.valueOf(sendModels.get(i).getJobPublishModel().getCrtTime()), "yyyy-MM-dd")) {
                    com.alibaba.fastjson.JSONObject data = new com.alibaba.fastjson.JSONObject();
                    //招聘公司
                    cn.hutool.json.JSONObject thing1 = new cn.hutool.json.JSONObject();
                    thing1.put("value", sendModels.get(i).getEnterpriseModel().getEnterpriseName());
                    data.put("thing1", thing1);
                    //招聘职位
                    cn.hutool.json.JSONObject thing2 = new cn.hutool.json.JSONObject();
                    thing2.put("value", sendModels.get(i).getJobPublishModel().getJobTitle());
                    data.put("thing2", thing2);
                    //薪资范围
                    cn.hutool.json.JSONObject thing3 = new cn.hutool.json.JSONObject();
                    thing3.put("value", "月薪" + sendModels.get(i).getJobPublishModel().getMinSalary() + "-" + sendModels.get(i).getJobPublishModel().getMaxSalary());
                    data.put("thing3", thing3);
                    //工作地点
                    cn.hutool.json.JSONObject thing4 = new cn.hutool.json.JSONObject();
                    thing4.put("value", sendModels.get(i).getJobPublishModel().getJobAddress());
                    data.put("thing4", thing4);
                    if (sendModels.get(i).getOpenid() != null) {
                        NewPosition(data, sendModels.get(i).getOpenid());
                    }
                }
            }
        } catch (Exception e) {
            log.error("定时任务出错", e);
        }
    }

    public static boolean isToday(String str, String formatStr) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            log.error("解析日期错误", e);
        }
        Calendar c1 = Calendar.getInstance();
        c1.setTime(date);
        int year1 = c1.get(Calendar.YEAR);
        int month1 = c1.get(Calendar.MONTH) + 1;
        int day1 = c1.get(Calendar.DAY_OF_MONTH);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(new Date());
        int year2 = c2.get(Calendar.YEAR);
        int month2 = c2.get(Calendar.MONTH) + 1;
        int day2 = c2.get(Calendar.DAY_OF_MONTH);
        if (year1 == year2 && month1 == month2 && day1 == day2) {
            return true;
        }
        return false;
    }
}
